﻿using ExitGames.Logging;
using ExitGames.Logging.Log4Net;
using log4net;
using log4net.Config;
using Photon.SocketServer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TaiDouCommon;
using TaiDouPhotonServer.Handlers;
using LogManager = ExitGames.Logging.LogManager;
namespace TaiDouPhotonServer
{
    //启动程序
    class TaiDouApplication:ApplicationBase
    {
        #region Instance
        private static TaiDouApplication _instance;
        public static TaiDouApplication Instance {
            get {
                return _instance;
            }
        }
        #endregion


        #region constants and fields
        private static readonly ILogger log = LogManager.GetCurrentClassLogger();

        #endregion

        #region Property
        //存放协议对应handler的字典
        private Dictionary<byte, HandlerBase> handlerDict = new Dictionary<byte, HandlerBase>();

        #endregion


        #region Methods

        //构造方法
        public TaiDouApplication() {
            _instance = this;
        }

        //客户端接入后创建
        protected override PeerBase CreatePeer(InitRequest initRequest)
        {
            return new ClientPeer(initRequest.Protocol, initRequest.PhotonPeer);           
        }


        //服务端启动
        protected override void Setup()
        {
            LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);
            GlobalContext.Properties["Photon:ApplicationLogPath"] = Path.Combine(this.ApplicationRootPath, "log");
            GlobalContext.Properties["LogFileName"] = "MS" + this.ApplicationName;
            XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(this.BinaryPath, "log4net.config")));

            log.Debug("application setup");
            RegisterHandlers();
        }

        //服务端挂掉
        protected override void TearDown()
        {
            log.Warn("application teardown");
        }

        /// <summary>
        /// 注册所有协议对应的handler
        /// </summary>
        void RegisterHandlers() {
            //handlerDict.Add((byte)OperationCode.Login, new LoginHandler());//登陆协议
            //handlerDict.Add((byte)OperationCode.GetServerList, new ServerHandler());//服务器列表协议
            //handlerDict.Add((byte)OperationCode.Register, new RegisterHandler());//用户注册协议
            //handlerDict.Add((byte)OperationCode.Role, new RoleHandler());//角色协议

            //handler的自动化注册
            //获取HandlerBase的全部子类(含自身)
            Type[] types = Assembly.GetAssembly(typeof(HandlerBase)).GetTypes();
            //循环遍历，取得子类，并实例化
            foreach (var type in types) {
                if (type.FullName.EndsWith("Handler")) {//判断是否是handler子类
                    Activator.CreateInstance(type);//实例化
                }
            }
        }

        //添加到字典中
        public void RegisterHandler(OperationCode code, HandlerBase handler) {
            handlerDict.Add((byte)code, handler);
        }


        /// <summary>
        /// 根据协议号获取对应的handler
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public HandlerBase GetHandlerByCode(byte code) {
            HandlerBase handler;
            handlerDict.TryGetValue(code, out handler);

            return handler;
        }
        #endregion
    }
}
